//
//  V2SelectDishesViewController.m
//  BaseProject
//
//  Created by 王洋 on 2021/4/27.
//  Copyright © 2021 王洋. All rights reserved.
//
#import "V2MenuCombCell.h"
#import "V2MenuSingleCell.h"
#import "V2CommonDishesModel.h"
#import "V2MenuSectionHeaderView.h"
#import "NormalTitleView.h"

#import "SubmitFieldOrderViewController.h"

#import "V2SelectDishesViewController.h"

@interface V2SelectDishesViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) NormalTitleView *headerView;

@property (nonatomic, strong) UITableView *tableview;

@property (nonatomic, strong) UIButton *handleBtn;

@property (nonatomic, strong) NSMutableArray <V2CommonDishesModel *>* sectionArray;

@end

@implementation V2SelectDishesViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initView];
    [self prepareData];

}

- (void)prepareData {
    
    self.sectionArray = @[].mutableCopy;

    CommonMenuModel *selModel = [[CommonMenuModel alloc] init];
    
    for (CommonMenuModel *model in self.menuArray) {
        if (model.isSelect) {
            selModel = model;
        }
    }
    
    //把各种类型拿出来
    NSMutableArray *dishesTypes = @[].mutableCopy;
    for (V2CommonMenuModel *f_model in selModel.dishesList) {
        if (![dishesTypes containsObject:@(f_model.dishesType)]) {
            [dishesTypes addObject:@(f_model.dishesType)];
        }
    }
    
    //确定有几个分组
    for (int i = 0; i < dishesTypes.count; i++) {
        V2CommonDishesModel *sectionModel = [[V2CommonDishesModel alloc] init];
        sectionModel.array = @[].mutableCopy;
        [self.sectionArray addObject:sectionModel];
    }
    
    //给每个组填充数据
    for (V2CommonMenuModel *f_model in selModel.dishesList) {
        [self.sectionArray[f_model.dishesType-1].array addObject:f_model];
    }
    
    [self.tableview reloadData];
}

- (void)initView {
    
    self.title = @"选择菜品";
    
    [self.view addSubview:self.tableview];
    
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(14);
        make.right.mas_equalTo(-14);
        make.top.mas_equalTo(0);
        make.bottom.mas_equalTo(-60-Bottom_SafeHeight);
    }];
    
    [self.view addSubview:self.handleBtn];
    [self.handleBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(14);
        make.right.mas_equalTo(-14);
        make.height.mas_equalTo(40);
        make.top.mas_equalTo(self.tableview.mas_bottom).offset(10);
    }];
    
    self.headerView =  [[NSBundle mainBundle] loadNibNamed:@"NormalTitleView"owner:nil options:nil].firstObject;
    self.headerView.titleLab.text = @"选择菜品";
    self.headerView.frame = CGRectMake(0, 0, TTScreenWidth, 50);
    self.tableview.tableHeaderView = self.headerView;
    self.headerView.autoresizingMask = UIViewAutoresizingNone;
    
    [self.tableview reloadData];
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.handleBtn pp_clipCorners:UIRectCornerAllCorners radius:self.handleBtn.frame.size.height/2];
    });
}

- (void)handleAction {
    
    NSInteger needSelCount = 0;
    NSInteger selCount = 0;
    for (V2CommonDishesModel* model in self.sectionArray) {
        
        for (V2CommonMenuModel *f_model in model.array) {
            if (f_model.dishesList.count > 0) {
                needSelCount++;
                for (V2CommonMenuModel *s_model in f_model.dishesList) {
                    if (s_model.isSelect) {
                        selCount++;
                    }
                }
            }
        }
    }
    
    if (needSelCount == selCount) {
        SubmitFieldOrderViewController *vc = [[SubmitFieldOrderViewController alloc] init];
        vc.model = self.model;
        vc.menuArray = self.menuArray;
        [self.navigationController pushViewController:vc animated:YES];
    } else {
        [SVProgressHUD showErrorWithStatus:@"请把组合菜品选完"];
        [SVProgressHUD dismissWithDelay:2];
    }
    

}


#pragma mark UITableviewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.sectionArray.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.sectionArray[section].array.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.sectionArray[indexPath.section].array[indexPath.row].dishesList.count > 0) {
        NSInteger cellArrayCount = self.sectionArray[indexPath.section].array[indexPath.row].dishesList.count;
        return cellArrayCount * 70 + 30;
    } else {
        return 70;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 40;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 5;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = UIColor.whiteColor;
    return view;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    V2MenuSectionHeaderView *sectionHeader = [[NSBundle mainBundle] loadNibNamed:@"V2MenuSectionHeaderView"owner:nil options:nil].firstObject;
    switch (section+1) {
        case V2CommonMenuModelDishesType_cold:{
            sectionHeader.mainTitleLab.text = @"冷菜";
        } break;
        case V2CommonMenuModelDishesType_hot:{
            sectionHeader.mainTitleLab.text = @"热菜";
        } break;
        case V2CommonMenuModelDishesType_main:{
            sectionHeader.mainTitleLab.text = @"主食";
        } break;
        case V2CommonMenuModelDishesType_give:{
            sectionHeader.mainTitleLab.text = @"赠送";
        } break;
        default:
            break;
    }
    return sectionHeader;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    WEAKSELF
    V2CommonMenuModel *cellModel = self.sectionArray[indexPath.section].array[indexPath.row];
    if (cellModel.dishesList.count > 0) {
        V2MenuCombCell *cell = [tableView dequeueReusableCellWithIdentifier:@"V2MenuCombCellID"];
        cell.selectionStyle =UITableViewCellSelectionStyleNone;
        cell.backgroundColor = UIColorHex(0xffffff);
        [cell fillWithModel:cellModel status:V2MenuSingleCellStatus_edit];
        
        cell.V2MenuCombCellBlock = ^(NSInteger index) {
          
            
            for (V2CommonMenuModel *model in weakSelf.sectionArray[indexPath.section].array[indexPath.row].dishesList) {
                model.isSelect = NO;
            }
            //组  一级
            weakSelf.sectionArray[indexPath.section].array[indexPath.row].dishesList[index].isSelect = YES;
            [weakSelf.tableview reloadData];
        };
        
        return cell;
    } else {
        V2MenuSingleCell *cell = [tableView dequeueReusableCellWithIdentifier:@"V2MenuSingleCellID"];
        cell.selectionStyle =UITableViewCellSelectionStyleNone;
        cell.bgView.hidden = YES;
        [cell fillWithModel:cellModel status:V2MenuSingleCellStatus_normal];
        return cell;
    }
}

- (UITableView *)tableview {
    if (!_tableview) {
        _tableview = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        _tableview.showsHorizontalScrollIndicator = NO;
        _tableview.showsVerticalScrollIndicator = NO;
        
        _tableview.estimatedSectionHeaderHeight = 0;
        _tableview.estimatedSectionFooterHeight = 0;
        _tableview.estimatedRowHeight = 0;
        
        _tableview.backgroundColor =  UIColorHex(0xf7f7f7);
        _tableview.showsVerticalScrollIndicator = NO;
        
        [_tableview registerNib:[UINib nibWithNibName:@"V2MenuCombCell" bundle:nil] forCellReuseIdentifier:@"V2MenuCombCellID"];
        [_tableview registerNib:[UINib nibWithNibName:@"V2MenuSingleCell" bundle:nil] forCellReuseIdentifier:@"V2MenuSingleCellID"];
    }
    return _tableview;
}

- (UIButton *)handleBtn {
    if (!_handleBtn) {
        _handleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        //        _handleBtn.backgroundColor = UIColor.redColor;
        [_handleBtn setBackgroundImage:[UIImage imageNamed:@"rect_orange"] forState:UIControlStateNormal];
        [_handleBtn addTarget:self action:@selector(handleAction) forControlEvents:UIControlEventTouchUpInside];
        [_handleBtn setTitle:@"确定菜品" forState:UIControlStateNormal];
        _handleBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    }
    return _handleBtn;
}

@end
